/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package blocagemcorreio;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Calebe
 */
public class mainBlocagem extends javax.swing.JFrame {

    private List listaCPD;
    private List listaAssinantes;
    private CPD cpd;
    private Assinante assinante;
    private ArrayList listaJasper;
    private int contador;
    
    /**
     * Creates new form mainBlocagem
     */
    public mainBlocagem() {
        initComponents();
        listaJasper = new ArrayList();
        contador = 0;
    }

    /**
     * Função pra imprimir o relatório
     */
    public void imprimir() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Conexao conexao = new Conexao();

                //Obtendo a lista de CPD`s do Correio
                listaCPD = conexao.listarCPDBlocagem();

                //Obtendo a lista de assinantes a ser enviada a revista
                listaAssinantes = conexao.listarAssinantesEtiquetas(jTextField_edCS.getText());

                for (int i = 0; i < listaCPD.size(); i++) {

                    //Barra de Progresso
                    jProgressBar.setVisible(true);
                    jProgressBar.setMinimum(0);
                    jProgressBar.setMaximum(listaAssinantes.size());

                    HashMap hashBlocagem = (HashMap) listaCPD.get(i);
                    cpd = new CPD();
                    cpd.setNomeCPD(hashBlocagem.get("nome").toString());
                    cpd.setCepInicial(hashBlocagem.get("cep_inicio").toString());
                    cpd.setCepFinal(hashBlocagem.get("cep_final").toString());

                    //Inserindo na lista os CPD's
                    listaJasper.add(hashBlocagem);


                    for (int j = 0; j < listaAssinantes.size(); j++) {
                        jProgressBar.setValue(j);
                        HashMap hashAssinante = (HashMap) listaAssinantes.get(j);
                        assinante = new Assinante();
                        assinante.setCodigo(hashAssinante.get("ass_codigo").toString());
                        assinante.setNome(hashAssinante.get("ass_nome_assinante").toString());
                        assinante.setLogradouro(hashAssinante.get("ass_logradouro").toString());
                        assinante.setTipoLogradouro(hashAssinante.get("ass_tipo_logradouro").toString());
                        assinante.setNumero(hashAssinante.get("ass_numero").toString());
                        assinante.setComplemento(hashAssinante.get("ass_complemento").toString());
                        assinante.setBairro(hashAssinante.get("ass_bairro").toString());
                        assinante.setCidade(hashAssinante.get("ass_cidade").toString());
                        assinante.setEstado(hashAssinante.get("ass_estado").toString());
                        assinante.setCep(hashAssinante.get("ass_cep").toString());

                        assinante.setCep(assinante.getCep().replaceAll("[\"\'-]", ""));

                        if (assinante.getCep().isEmpty() || assinante.getCep().contains("\"\'")) {
                            assinante.setCep("0");
                        }

                        if (Integer.parseInt(assinante.getCep()) >= Integer.parseInt(cpd.getCepInicial())
                                && Integer.parseInt(assinante.getCep()) <= Integer.parseInt(cpd.getCepFinal())) {
                            
                            //Insere na lista os assinantes em cada CPD a qual pertence na ordem de CEP
                            listaJasper.add(hashAssinante);
                            
                            /**Monitora a quantidade de Assinantes no CPD, não pode passar de
                            35 pois o Correio não permite devido ao transporte*/
                            contador += 1;

                            if (contador == 35) {
                                //Insere o CPD novamente pois tem mais que 35 assinantes ativos neste CPD
                                listaJasper.add(hashBlocagem);
                                contador = 0;
                            }
                        }
                    }
                    contador = 0;
                }
                
                //Barra de progresso
                jProgressBar.setValue(listaAssinantes.size());
                jProgressBar.setString("Aguarde! Gerando PDF do Relatório.");
                jProgressBar.setStringPainted(true);
                
                //Montando o Bean Collection Data Source para o iReport fazer o relatorio
                JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(listaJasper);

                // Parametros do relatorios     
                Map parameters = new HashMap();


                try {
                    
                    //Pegando o caminho do relatorio para compilar
                    //File file = new File(getClass().getResource("/relatorios/Etiquetas_Assinantes_Nova_Blocagem.jrxml").getFile());                                       
//                    File file = new File(getClass().getResource("E:\\Banco de Dados NOVO\\BlocagemCorreio\\src\\relatorios\\Etiquetas_Assinantes_Nova_Blocagem.jrxml").getFile());                                       
                   
                    //PC - Calebe
                    //String layout = "O:\\Relatorios\\Blocagem\\Etiquetas_Assinantes_Nova_Blocagem.jrxml";
                    
                    //PC - Thiago
                    //String layout = "X:\\Relatorios\\Blocagem\\Etiquetas_Assinantes_Nova_Blocagem.jrxml";
                    
                    //PC - Portella
                    String layout = "Q:\\Relatorios\\Blocagem\\Etiquetas_Assinantes_Nova_Blocagem.jrxml";
                    
                    //Gerando o jasper design  
                    JasperDesign desenho = JRXmlLoader.load(layout);

                    //Compila o relatório  
                    JasperReport relatorio = JasperCompileManager.compileReport(desenho);

                  //  JasperReport report = JasperCompileManager.compileReport(file.getPath());

                    //Imprimindo o relatorio
                    JasperPrint print = JasperFillManager.fillReport(relatorio, null, new JRBeanCollectionDataSource(listaJasper));
                    
                    //Mostrando o relatorio na Tela
                    JasperViewer viewer = new JasperViewer(print);
                    viewer.setVisible(true);

                } catch (JRException e) {
                    System.out.println(e.getMessage());
                    System.out.println("PRINTSTACKTRACE = ");
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField_edCS = new javax.swing.JTextField();
        jButton_imprimir = new javax.swing.JButton();
        jProgressBar = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Blocagem Correios");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Edição Classic Show:");

        jButton_imprimir.setText("Imprimir");
        jButton_imprimir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton_imprimirMouseClicked(evt);
            }
        });
        jButton_imprimir.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jButton_imprimirKeyPressed(evt);
            }
        });

        jProgressBar.setFont(new java.awt.Font("Tahoma", 1, 10)); // NOI18N
        jProgressBar.setMaximum(5000);
        jProgressBar.setToolTipText("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextField_edCS, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(107, 107, 107)
                                .addComponent(jLabel1)))
                        .addGap(18, 18, 18)
                        .addComponent(jButton_imprimir)
                        .addGap(0, 12, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField_edCS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton_imprimir))
                .addGap(18, 18, 18)
                .addComponent(jProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_imprimirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton_imprimirMouseClicked
        imprimir();
    }//GEN-LAST:event_jButton_imprimirMouseClicked

    private void jButton_imprimirKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jButton_imprimirKeyPressed
        imprimir();
    }//GEN-LAST:event_jButton_imprimirKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(mainBlocagem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(mainBlocagem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(mainBlocagem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(mainBlocagem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new mainBlocagem().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_imprimir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JProgressBar jProgressBar;
    private javax.swing.JTextField jTextField_edCS;
    // End of variables declaration//GEN-END:variables
}
